package com.kjs.web.service.impl;

import com.kjs.common.resultModel.JwtUser;
import com.kjs.common.resultModel.LoginResult;
import com.kjs.common.tools.*;
import com.kjs.execptionless.*;
import com.kjs.web.dao.mapper.*;
import com.kjs.web.pojo.*;
import com.kjs.web.service.ICustomersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author xuedingjiexueergou@gmail.com
 * @date 2018/10/12 10:53
 */
@Service
@Slf4j
public class CustomersServiceImpl implements ICustomersService {

    @Autowired
    private ICustomersMapper customersMapper;

    @Value("${jwt.exp}")
    private int jwtExp; // 超时天数
    @Value("${jwt.jwtIss}")
    private String jwtIss;
    @Value("${jwt.cert}")
    private String cert;
    @Value("${jwt.auth.head}")
    private String jwtHeader; // 头部的json字符串的base64值

    @Override
    public LoginResult login(String userName, String pwd) {
        Customers customers = new Customers();
        customers.setTelphone(userName);
        customers.setPassword(pwd);
        long exp = System.currentTimeMillis() + jwtExp * 86400000l; // +30天
        String randomStr = StringCodec.generateAlpha(RandomCodec.random(16, 32));
        customers = customersMapper.getByUserNameAndPwd(customers);
        if (null == customers) {
            throw new BusinessException(ExceptionMsg.DataNotFound);
        }
        String id = UUID.randomUUID().toString();
        // 生成JWT
        String jwtStr = JwtTokenUtil.accessToken(jwtIss, exp, randomStr, id, cert);
        //  保存JwtUser
        JwtUser jwtUser = new JwtUser();
        jwtUser.setId(customers.getId());
        jwtUser.setSalt(customers.getSalt());
        jwtUser.setUid(customers.getId());
//        redisUtil.set(RedisCatalogConst.TOKEN + ":" + id, jwtUser.getId());
//        jwtUserCacheService.save(jwtUser);
        LoginResult loginResult = new LoginResult();
        loginResult.setExpire(exp);
        loginResult.setRandom(randomStr);
        loginResult.setToken(jwtHeader + " " + jwtStr);
        loginResult.setKey(cert);
        loginResult.setJwtId(jwtUser.getId());

        return loginResult;
    }

    @Override
    public Customers get(int id) {
        Customers customers = customersMapper.getById(id);
        if (null == customers) {
            throw new BusinessException(ExceptionMsg.DataNotFound);
        }

        return customers;
    }

}
